package model

import (
	"errors"
	"fmt"
	"github.com/xfchenjian/gossdb"
	"log"
)

type Account struct {
	Username string `json:"username"`
	Passwd   string `json:"passwd"`
	Channel  string `json:"channel"`
	Mobile   string `json:"mobile"`
	Platform int8   `json:"platform"`
	Uid      uint32 `json:"uid"`
}

func AccountExist(client *gossdb.Client, acc string, ch string) (bool, error) {
	name := ChannelPrefix + ch
	return client.Hexists(name, acc)
}

func NewUid(client *gossdb.Client) uint32 {
	uid, err := client.Incr(uidIndexKey, 1)
	if err != nil {
		log.Fatal("generate new uid fail, err: ", err.Error())
		return uint32(0)
	}

	return uid.UInt32()
}

func NewAccount() *Account {
	return &Account{}
}

func Regist(client *gossdb.Client, accout *Account) error {
	name := ChannelPrefix + accout.Channel
	err := client.Hset(name, accout.Username, accout.Uid)
	if err != nil {
		return err
	}

	key := fmt.Sprintf("%d", accout.Uid)
	exist, _ := client.Hexists(accountDB, key)
	if exist {
		return errors.New("registed repeat")
	}

	err = client.Hset(accountDB, key, toJson(accout))
	return err
}

func GetAccount(user string, ch string) *Account {
	acc := NewAccount()

	acc.Username = user
	acc.Passwd = ""
	acc.Uid = 0

	return acc
}
